import { constRoutes, resetRouter } from '@/router'

import { loginAPI, getProfileAPI } from '@/api/user'
import { setTokenCookie, getTokenCookie, removeTokenCookie } from '@/utils/auth'

export default {
  namespaced: true,
  state() {
    return {
      token: getTokenCookie() || '', // 登录令牌，优先从cookie中获取
      profile: {}, // 登录用户的角色和权限等信息
      menuList: [...constRoutes] // 左侧菜单列表
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      // 将令牌保存到cookie中
      setTokenCookie(token)
    },
    clearUserInfo(state) {
      state.token = ''
      state.profile = {}
      // 删除cookie中的令牌
      removeTokenCookie()
    },
    clearMenuList(state) {
      state.menuList = [...constRoutes]
      // 重置路由系统
      resetRouter()
    },
    setProfile(state, profile) {
      state.profile = profile
    },
    setMenuList(state, filterRouter) {
      state.menuList = [...state.menuList, ...filterRouter]
    }
  },
  actions: {
    async getToken(context, { username, password }) {
      const res = await loginAPI({ username, password })
      // 保存令牌
      context.commit('setToken', res.token)
    },
    async getProfile(context) {
      const res = await getProfileAPI()
      // 保存登录人用户、角色和权限信息
      console.log(res)
      context.commit('setProfile', { ...res })
    }
  }
}
